<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;
use think\Db;
use app\common\library\Config;
use think\helper\Time;

class Sendwx extends Command
{


    //命令描述
    protected function configure()
    {
        $this->setName('sendwx')->setDescription('work time run and wx');
    }

    //所要执行的命令
    protected function execute(Input $input, Output $output)
    {
        //开始发送
        // Cache::clear();
        Config::config();
        cache('run_status', 'no');
//        $this->login_wage();//计算考勤奖金
//        exit;

        if (cache('run_status') == 'no') {
            cache('run_status', 'yes');
            $output->writeln("stories run start");
            $this->stories();
            if (cache('last_time') < time()) {
                //30分钟进行一次
                $output->writeln("project  run ");
                $this->project();//项目时间计算

                $output->writeln("day_user  run ");
                $this->day_user();//每日工作时间
                $output->writeln("work_time run ");
                $this->work_time();//计算本月分配的工时
                cache('last_time', time() + 60 * 30);
            } else {
                $output->writeln("user no run ");
            }
            //$output->writeln("last_time_d:".cache('last_time_d').'-new_time:'.time());
            if (cache('last_time_d') < time()) {
                //12小时清理一次
                $output->writeln("clear  run ");
                $output->writeln("project_user_clear  run ");
                $this->project_user_clear();//清理项目退出用户
                $output->writeln("wx_msg_clear  run ");
                $this->wx_msg_clear();//清理微信模板消息
                $output->writeln("login_wage  run ");
                $this->login_wage();//计算考勤奖金
                $output->writeln("user  run ");
                $this->user();//用户工资核算
                cache('last_time_d', time() + 86400 / 3);
            } else {
                $output->writeln("clear no run ");
            }
            $output->writeln("wx_send  run ");
            $this->wx_send();//推送微信消息
            cache('run_status', 'no');
        } else {
            $output->writeln("task runing ");
        }
        $output->writeln("work time run and wx  over");
    }

    protected function project_user_clear()
    {
        $list = DB::view('project_user', 'id')
            ->view('auth_group_access', 'uid', 'project_user.uid=auth_group_access.uid')
            ->where('auth_group_access.group_id', 14)
            ->select();
        foreach ($list as $item) {
            DB::name('project_user')->where('uid', $item['uid'])->delete();
        }
    }

    protected function wx_msg_clear()
    {
        //30天以前的清理掉，微信模板消息
        DB::name('wx_msg')->where('c_time', '<', time() - 86400 * 30)->where('status', 2)->delete();
        //考勤365天以前的清理掉，考勤
        DB::name('workreg_d')->where('d_time', '<', time() - 86400 * 365)->delete();
        //30天以前的清理掉，定位信息
        DB::name('workreg')->where('c_time', '<', time() - 86400 * 30)->delete();


    }

    protected function wx_send()
    {
        $project_model = config('param.project_model');
        cache('access_token2', Db::name('config')->where('id', 56)->value('value'));
        $list = Db::name('wx_msg')
            ->where('status', '=', 1)
            ->select();
        foreach ($list as $item) {
            // dump($item);
            $user = DB::name('project_user')->where('project_id', $item['project_id'])->select();
            //dump($user);
            foreach ($user as $info) {
                $openid = DB::name('admin')->where('id', $info['uid'])->value('openid');
                if ($openid) {
                    $data['project_name'] = DB::name('project')->where('id', $item['project_id'])->value('title');
                    if ($item['model_id'] == 4) {
                        $data['model_name'] = '文档';
                    } else {
                        $data['model_name'] = $project_model[$item['model_id']];
                    }

                    $data['time'] = date('Y-m-d  H:i:s', $item['c_time']);
                    $data['openid'] = $openid;
                    if ($item['uid']) {
                        $data['nickname'] = '[操作人员:' . DB::name('admin')->where('id', $item['uid'])->value('nickname') . ']';
                    } else {
                        $data['nickname'] = '';
                    }
                    $data['info'] = $item['info'];
                    $data['uid'] = $info['uid'];
                    if ($item['model_id'] == 4) {
                        $data['status'] = '--';
                        $data['info_title'] = DB::name('doc')->where('id', $item['stories_id'])->value('title');
                        $data['url'] = 'https://cdn.weibuyun.com/wx/doc/index?id=' . $item['stories_id'];
                    } else {

                        $status = config('param.model_' . $item['model_id'] . '_status');
                        //dump($status);
                        //  dump( $status[$data['status']]);
                        //dump($item);

                        $data['status'] = $item['model_status'] ? $status[$item['model_status']] : '--';
                        $data['info_title'] = DB::name('stories')->where('id', $item['stories_id'])->value('title');
                        $data['url'] = 'https://cdn.weibuyun.com/wx/stories/index?stories_id=' . $item['stories_id'];
                    }
                    //dump($data);
                    $data['tmid'] = config('param.tmid');
                    $data['msgid'] = $this->send($data);
                    $data['msg_id'] = $item['id'];
                    if ($data['msgid'] == 0) {
                        $data['status'] = 7;
                    } else {
                        $data['status'] = 2;
                    }
                    //exit;
                    DB::name('wx_msg_info')->strict(false)->insert($data);
                }

            }
            DB::name('wx_msg')->where('id', $item['id'])->update(['status' => 2]);
        }
    }

    protected function send($msg)
    {
        \think\facade\Log::write(json_encode($msg), 'INFO');
        //echo "access_token=" . cache('access_token2');
        $host = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . cache('access_token2');
        $sdata = array();
        $sdata['template_id'] = $msg['tmid'];
        $sdata['touser'] = $msg['openid'];
        $sdata['url'] = $msg['url'];
        $data['first']['value'] = '你好,项目有新的变化' . $msg['nickname'];
        $data['first']['color'] = "#1E9FFF";
        $data['keyword1']['value'] = $msg['project_name'];
        $data['keyword1']['color'] = "#1E9FFF";
        $data['keyword2']['value'] = $msg['status'];
        $data['keyword2']['color'] = "#FFB800";
        $data['keyword3']['value'] = $msg['info_title'];
        $data['keyword3']['color'] = "#1E9FFF";
        $data['keyword4']['value'] = $msg['time'];
        $data['keyword4']['color'] = "#1E9FFF";
        $data['remark']['value'] = $msg['model_name'] . '发生变化:' . strip_tags($msg['info']);
        $data['remark']['color'] = "#FF5722";
        $sdata['data'] = $data;
//        echo config('param.domain');
        // dump($sdata);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $host);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sdata));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        // dump($re);
        if (curl_errno($ch)) {
            //  dump(curl_error($ch));
            //  \Think\Log::write(json_encode(curl_errno($ch)), 'INFO');
            // \Think\Log::write(jcurl_errno($ch), 'INFO');
            // \think\facade\Log::write(json_encode(curl_errno($ch)), 'WX_MESSAGE_ERROE');
        }
        \think\facade\Log::write($re, 'WX_MESSAGE');
        curl_close($ch);
        if ($re['errcode'] == 0) {
            return $re['msgid'];
        } else {
            return 0;
        }

    }

    protected function stories()
    {
        list($start, $end) = Time::month();
        $list = Db::name('stories')
            ->where('s_time', '>=', $start)
            ->where('s_time', '<=', $end)
            ->select();
        foreach ($list as $item) {
            $data = array();
            $data['id'] = $item['id'];
            $w_time = DB::name('work_time')
                ->where('stories_id', $item['id'])
                ->where('model_id', $item['model_id'])
                ->where('uid', $item['touid'])
                ->sum('w_time');
            DB::name('stories')->where('id', $item['id'])->update(['w_time' => $w_time]);
        }
    }

    protected function project()
    {
        $list = Db::name('project')
            ->where('status', '<>', 10)
            ->select();
        foreach ($list as $item) {
            $data = array();
            $data['id'] = $item['id'];
            $w_time = DB::name('stories')
                ->where('project_id', $item['id'])
                ->sum('w_time');
            $p_time = DB::name('stories')
                ->where('project_id', $item['id'])
                ->sum('p_time');
            if ($w_time == 0) {
                $w_time = 0;
            } else {
                $w_time = $w_time;
            }
            if ($p_time == 0) {
                $p_time = 0;
            } else {
                $p_time = $p_time;
            }
            DB::name('project')->where('id', $item['id'])->update(['w_time' => $w_time, 'p_time' => $p_time]);
        }
    }

    protected function user()
    {
        list($start, $end) = Time::month();
        /*用户工资核算*/

        $list = Db::name('auth_group_access')
            ->where('group_id', '=', 11)
            ->select();//得出用户列表
        //  dump($list);

        foreach ($list as $item) {
            //没有信息先建立信息
            $map['uid'] = $item['uid'];
            $map['m_time'] = $start;
            $month_wage = DB::name('user_work')->where($map)->find();
            $user = DB::name('user_base')->where('uid', $item['uid'])->find();
            //dump($month_wage);
            //计算本月出勤奖金
            $login_wage = DB::name('workreg_d')
                ->where('uid', $item['uid'])
                ->where('d_time', '>=', $start)
                ->where('d_time', '<=', $end)
                ->where('wage_status', 2)
                ->sum('work_wage');//汇总
            //dump($month_wage);
            //dump($login_wage);
            if ($month_wage) {
                // 只更新出勤奖金和基本工资;
                $data2['login_wage'] = $login_wage;
                $data2['base_wage'] = $user['base_wage'];
                $data2['sum_wage'] =$data2['base_wage']+$data2['login_wage']+$month_wage['change_wage']+$month_wage['work_wage'];//
                DB::name('user_work')->where('id', $month_wage['id'])->update($data2);
            } else {
                //新增
                $data2['login_wage'] = $login_wage;//出勤
                $data2['uid'] = $item['uid'];
                $data2['m_time'] = $start;
                $data2['change_wage'] = 0;//调整
                $data2['base_wage'] = $user['base_wage'];//基本
                $data2['work_wage'] = 0;//绩效
                $data2['sum_wage'] = $data2['base_wage'] + $login_wage;
                DB::name('user_work')->insert($data2);
            }
            //计算用户本月应得项目绩效
            $project_list = DB::view('project', 'id')
                ->view('project_user', 'work_wage', 'project_user.project_id=project.id')
                ->where('uid', $item['uid'])
                ->where('status', 9)//交付和维护
                ->where('ok_time', '>', $start)
                ->where('ok_time', '<', $end)
                ->where('ok_status', 1)//没有结算过的
                ->select();//得出本月完成的项目
            // dump($project_list);
            foreach ($project_list as $item2) {
                // dump($item2);
                //工作时间
                $data['w_time'] = Db::name('stories')
                    ->where('status', 5)
                    ->where('touid', $item['uid'])
                    ->where('project_id', $item2['id'])
                    ->sum('w_time');
                //预期时间
                $data['p_time'] = Db::name('stories')
                    ->where('project_id', $item2['id'])
                    ->where('touid', $item['uid'])
                    ->where('status', 5)
                    ->sum('p_time');
                //超时扣除

                if ($data['p_time'] < $data['w_time']) {
                    $data['out_time'] = $data['w_time'] - $data['p_time'];//超时
                } else {
                    $data['out_time'] = 0;
                }
                $data['uid'] = $item['uid'];
                $data['m_time'] = $start;
                $data['project_id'] = $item2['id'];
                $work_wage = $item2['work_wage'];//小时绩效
                $data['run_wage'] = $work_wage * $data['p_time'];//得
                $data['out_wage'] = $work_wage * $data['out_time'];//扣
                $data['ok_wage'] = $data['run_wage'] - $data['out_wage'];//到手绩效
                $data['work_wage'] = $work_wage;//绩效标准
                DB::name('project_work')->insert($data);//存入项目明细
                DB::name('project')->where('id', $item2['id'])->update(['ok_status' => 2]);//标记为结算
                //本月工资增加
                $map['uid'] = $item['uid'];
                $map['m_time'] = $start;
                $month_wage = DB::name('user_work')->where($map)->find();
                $data2['work_wage'] = $month_wage['work_wage'] + $data['ok_wage'];
                $data2['sum_wage'] = $month_wage['sum_wage'] + $data['ok_wage'];
                DB::name('user_work')->where('id', $month_wage['id'])->update($data2);
            }
        }

    }

    protected function login_wage()
    {
        /*用户日时间核算*/
        list($s_day, $e_day) = Time::yesterday();
        $map['d_time'] = $s_day;
        $list = DB::name('workreg_d')
            ->where($map)
            ->select();
        $login_time = config('param.login_time');
        //1:考勤表建立
        //2:请事假
        //3:节假日
        //4:正常考勤
        //5:周六日
        //6:请病假
        //7:其他假

        foreach ($list as $item) {
            //dump($item);
            $user = DB::name('user_base')->where('uid', $item['uid'])->find();
            $data = [];
            switch ($item['status']) {
                case 2:
                    //事假
                    $data['work_wage'] = $user['leave_wage'];
                    break;
                case 6:
                    //病假
                    $data['work_wage'] = $user['sick_wage'];
                    break;
                case 4:
                    //正常
                    $data['work_wage'] = $user['day_wage'];
                    $am_in = strtotime(date('Ymd' . $login_time[1] . '59', $item['am_in']));
                    // echo date('Ymd' . $login_time[1] . '59', $item['am_in']);
                    $wage = 0;
                    if ($item['am_in'] > 0 && $item['am_in'] <= $am_in) {
                        $wage = $wage + $user['login_wage'];
                    }
                    $am_out = strtotime(date('Ymd  ' . $login_time[2] . '00', $item['am_out']));
                    if ($item['am_out'] > 0 && $item['am_out'] >= $am_out) {
                        $wage = $wage + $user['login_wage'];
                    }
                    $fm_in = strtotime(date('Ymd  ' . $login_time[3] . '59', $item['fm_in']));
                    if ($item['fm_in'] > 0 && $item['fm_in'] <= $fm_in) {
                        $wage = $wage + $user['login_wage'];
                    }
                    $fm_out = strtotime(date('Ymd  ' . $login_time[4] . '00', $item['fm_out']));
                    if ($item['fm_out'] > 0 && $item['fm_out'] >= $fm_out) {
                        $wage = $wage + $user['login_wage'];
                    }
                    $data['work_wage'] = $data['work_wage'] + $wage;
                    break;
                default:
                    $data['work_wage'] = 0;
            }
            $data['wage_status'] = 2;
            DB::name('workreg_d')->where('id', $item['id'])->update($data);
            //dump($data);
        }
    }

    protected function day_user()
    {
        /*用户日时间核算*/
        list($s_day, $e_day) = Time::today();
        $list = Db::name('auth_group_access')
            ->where('group_id', '=', 11)
            ->select();
        foreach ($list as $item) {
            $map['uid'] = $item['uid'];
            $map['c_time'] = $s_day;
            $info = DB::name('work_user_time')
                ->where($map)
                ->find();
            $data['w_time'] = Db::name('work_time')
                ->where('c_time', '>=', $s_day)
                ->where('c_time', '<=', $e_day)
                ->where('uid', $item['uid'])
                ->sum('w_time');
            $data['w_time'] = $data['w_time'];//转化成小时
            $data['model_1'] = Db::name('work_time')
                ->where('c_time', '>=', $s_day)
                ->where('c_time', '<=', $e_day)
                ->where('uid', $item['uid'])
                ->where('model_id', 1)
                ->count();
            $data['model_2'] = Db::name('work_time')
                ->where('c_time', '>=', $s_day)
                ->where('c_time', '<=', $e_day)
                ->where('model_id', 2)
                ->where('uid', $item['uid'])
                ->count();
            $data['model_3'] = Db::name('work_time')
                ->where('c_time', '>=', $s_day)
                ->where('c_time', '<=', $e_day)
                ->where('model_id', 3)
                ->where('uid', $item['uid'])
                ->count();
            if ($info) {
                DB::name('work_user_time')->where($map)->update($data);
            } else {
                $data['uid'] = $item['uid'];
                $data['c_time'] = $s_day;
                DB::name('work_user_time')->insert($data);
            }
        }
    }

    protected function work_time()
    {
        list($s_day, $e_day) = Time::month();
        $list = Db::name('auth_group_access')
            ->where('group_id', '=', 11)
            ->select();
        foreach ($list as $item) {
            $map['uid'] = $item['uid'];
            $map['m_time'] = $s_day;
            $info = DB::name('user_work')
                ->where($map)
                ->find();
            //得到当前人员的需求时间
            $data['work_time'] = Db::name('work_time')
                ->where('c_time', '>=', $s_day)
                ->where('c_time', '<=', $e_day)
                ->where('uid', $item['uid'])
                ->where('model_id', 1)
                ->sum('w_time');
            if ($info) {
                DB::name('user_work')->where($map)->update($data);
            }
        }
    }

}